/**
 * Copyright (c) 2011 ~ 2013 Deepin, Inc.
 *               2011 ~ 2013 jouyouyun
 *
 * Author:      jouyouyun <jouyouwen717@gmail.com>
 * Maintainer:  jouyouyun <jouyouwen717@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 **/

package main

import (
	"fmt"
	"github.com/BurntSushi/xgbutil"
	"github.com/BurntSushi/xgbutil/keybind"
	"github.com/BurntSushi/xgbutil/xevent"
)

var X *xgbutil.XUtil

func GrabKey(shortcut string) {
	if len(shortcut) <= 0 {
		fmt.Println("grab key args failed...")
		return
	}

	mod, keys, err := keybind.ParseString(X, shortcut)
	fmt.Printf("state: %d, detail: %d\n", mod, keys[0])
	if err != nil {
		fmt.Printf("grab parse shortcut string failed: %s\n", err)
		return
	}

	err = keybind.GrabChecked(X, X.RootWin(), mod, keys[0])
	if err != nil {
		fmt.Printf("Grab '%s' Failed: %s\n", shortcut, err)
		return
	}
}

func UngrabKey(shortcut string) {
	if len(shortcut) <= 0 {
		fmt.Println("ungrab key args failed...")
		return
	}

	mod, keys, err := keybind.ParseString(X, shortcut)
	if err != nil {
		fmt.Printf("ungrab parse shortcut string failed: %s\n", err)
		return
	}

	keybind.Ungrab(X, X.RootWin(), mod, keys[0])
}

func ListenKeyEvent() {
	xevent.KeyPressFun(
		func(X *xgbutil.XUtil, e xevent.KeyPressEvent) {
			fmt.Printf("State: %d, Detail: %d\n",
				e.State, e.Detail)
			mod, keycode := keybind.DeduceKeyInfo(e.State, e.Detail)
			fmt.Printf("Deduce State: %d, Detail: %d\n",
				mod, keycode)
			if keybind.KeyMatch(X, "q", e.State, e.Detail) {
				fmt.Println("Super+Q")
				UngrabKey("mod4-q")
			}

			if keybind.KeyMatch(X, "k", e.State, e.Detail) {
				fmt.Println("Super+K")
				GrabKey("mod4-q")
			}
		}).Connect(X, X.RootWin())
}

func main() {
	var err error

	X, err = xgbutil.NewConn()
	if err != nil {
		fmt.Println("Get New X Connection Failed:", err)
		return
	}
	keybind.Initialize(X)

	GrabKey("mod4-q")
	GrabKey("mod4-k")
	GrabKey("mod4-l")
	GrabKey("control-Control_L")

	ListenKeyEvent()

	xevent.Main(X)
}
